package com.zsc.wxm.ysh.anjo.sms.controller;

import com.zsc.wxm.ysh.anjo.result.Result;
import com.zsc.wxm.ysh.anjo.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * 短信管理
 * @author playmaker
 * @since 2021-01-13
 */
@RestController
@RequestMapping("/common/sms")
@Api(tags = "发送短信接口")
public class SmsController {

    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @PostMapping("/send-message")
    @ApiOperation(value = "发送短信",httpMethod = "POST")
    public Result sendMessage(@RequestParam("phone") @ApiParam("电话号码") String phone) throws UnsupportedEncodingException {
        //清除缓存
        redisTemplate.delete(phone);

        //生成4位验证码
        String checkCode = RandomStringUtils.randomNumeric(4);

        //设置10分钟有效
        redisTemplate.opsForValue().set(phone,checkCode,10, TimeUnit.MINUTES);

        //发短信
        smsService.send(phone,"{\"code\":\""+checkCode+"\"}");

        return Result.ok("发送短信成功");

    }
}
